﻿namespace Pyramid.Hardware.Operations
{
    using System.Collections.Generic;
    using System.Linq;

    public class AddOperation
        : Operation
    {
        private readonly IEnumerable<ILine> outputs;
        private readonly ILine overflowFlag;

        public AddOperation(IEnumerable<ILine> inputBusA, IEnumerable<ILine> inputBusB)
            : base(inputBusA, inputBusB)
        {
            var outputList = new List<ILine>();

            var aLines = inputBusA.ToArray();
            var bLines = inputBusB.ToArray();

            FullAdder lastAdder = null;

            for (int lineIndex = 0; lineIndex < aLines.Length; lineIndex++)
            {
                var adder = new FullAdder(
                                    aLines[lineIndex],
                                    bLines[lineIndex],
                                    lastAdder != null
                                        ? lastAdder.Carry
                                        : FixedInputLine.Unknown);

                outputList.Add(adder.Sum);

                lastAdder = adder;
            }

            this.outputs = outputList;
            this.overflowFlag = lastAdder.Carry;
        }

        public override IEnumerable<ILine> OutputBus
        {
            get
            {
                return outputs;
            }
        }

        public override ILine OverflowFlag
        {
            get
            {
                return this.overflowFlag;
            }
        }
    }
}
